<template>
  <div class="edit-wrapper">
    <div class="edit-header">
      <div class="go-back" @click="goBack">
        <i class="iconfont icon-left"></i>
        <span>文章管理</span>
      </div>
      <div class="title">
        <input type="text" v-model="article.title" placeholder="请输入文章标题" />
      </div>
      <div class="btn-group">
        <button class="draft">保存草稿</button>
        <button class="publish" @click.prevent="publishClick">发布文章</button>
      </div>
    </div>
    <div class="edit-content">
      <mavon-editor
        style="width: 100vw; height: 100%; min-height: 0"
        v-model="article.content"
      ></mavon-editor>
    </div>
    <Modal
      @queryClick="queryClick"
      :is-show-modal.sync="isShowModal"
      :classify="article.classify"
      :tags="article.tags"
      :imgUrl="article.imgUrl"
      :description="article.description"
    />
  </div>
</template>

<script>
import api from '../../../api/blog'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import Modal from './modal.vue'
export default {
  name: 'create',
  data() {
    return {
      article: {
        title: '',
        content: '',
        classify: '',
        tags: [],
        iimgUrl: '',
        description: ''
      },
      isEdit: false,
      isShowModal: false
    }
  },
  components: {
    mavonEditor,
    Modal
  },
  methods: {
    goBack() {
      this.$router.push('/admin/content')
    },

    // 文章发布/更新
    async publishClick() {
      if (!this.article.title) {
        this.$Message.error('文章标题不能为空')
        return
      }
      if (!this.article.content) {
        this.$Message.error('文章内容不能为空')
        return
      }
      this.isShowModal = true
    },

    // 弹窗确认
    async queryClick(value) {
      const params = {
        title: this.article.title,
        content: this.article.content,
        createTime: new Date().toLocaleDateString(),
        ...value
      }
      console.log(this.isEdit, params)
      try {
        const res = this.isEdit
          ? await api.updatePost(Object.assign(params, { id: this.article.id }))
          : await api.addPost(params)
        if (res.code === 200) {
          this.$Message.success(res.message)
          this.$router.push('/admin/content')
        } else {
          this.$Message.error(res.message)
        }
      } catch (err) {
        console.err(err)
      }
    }
  },
  created() {
    if (Object.keys(this.$route.params).length) {
      this.isEdit = true
      this.article = this.$route.params
    }
  }
}
</script>
